package com.he.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: TODO
 * @Author: HCL
 * @Date: 2025/1/2 14:35
 */
@Service
public class WeightServiceImpl implements WeightService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void saveDataToRedis() {
        // 获取当前时间
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME);

        // 构建 Redis 键
        String redisKey = "weight:1A1";

        // 使用 Hash 存储
        stringRedisTemplate.opsForHash().put(redisKey, timestamp, String.valueOf(199.5));//可以设置过期时间
    }

    // 获取时间范围内的所有重量
    public Map<String, String> getWeightsInRange(String scaleName, String startTime, String endTime) {
        Map<String, String> result = new HashMap<>();
        String redisKey = scaleName;

        // 获取 Hash 中的所有数据
        Map<Object, Object> weights = stringRedisTemplate.opsForHash().entries(redisKey);

        // 遍历并过滤时间范围
        for (Map.Entry<Object, Object> entry : weights.entrySet()) {
            String time = (String) entry.getKey();
            String weight = (String) entry.getValue();
            if (time.compareTo(startTime) >= 0 && time.compareTo(endTime) <= 0) {
                result.put(time, weight);
            }
        }
        return result;
    }
}
